package com.awspaas.user.apps.processforsap.util;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.common.profile.StringUtil;
import com.awspaas.user.apps.processforsap.model.MessageHeader;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public abstract class ParentInterface {
    //接口原数据
    public JSONObject sendData;
    //最终发送数据
    public String resultSendData;
    //最终返回数据
    public String returnData;
    //配置数据
    public MessageHeader messageHeader;
    //最终结果
    public boolean resultType = true;

    public ParentInterface(JSONObject jsonObject) {
        /**
         * 处理请求数据
         */
        JSONObject messageHeader = jsonObject.getJSONObject("MessageHeader");
        //获取接口编码
        String interfaceId = messageHeader.getString("Interface_ID");
        String uuid = messageHeader.getString("UUID");
        String messageId = messageHeader.getString("MessageId");
        String disId = messageHeader.getString("DisId");
        MessageHeader mhModel = new MessageHeader(interfaceId, uuid, messageId, disId);
        this.messageHeader = mhModel;
        String bindId = jsonObject.getString("BINDID");
        if (StringUtil.isEmpty(bindId)) {
            throw new BPMNError("0331", "未获取到流程实例ID，无法获取原数据，请注意核查！");
        } else {
            sendData(jsonObject);
        }
    }

    /**
     * 逻辑处理，组装原始接口发送数据
     */
    private void sendData(JSONObject jsonObject) {
        List<BO> list = this.messageHeader.getGirdConfigBo();

        String bindId = jsonObject.getString("BINDID");
        //判断是否带审批信息
        String spdm = jsonObject.getString("SPDM");


        JSONObject returnJsonObject = new JSONObject();
        JSONObject hearder = new JSONObject();
        hearder.put("UUID", this.messageHeader.getUUID());
        hearder.put("DisId", this.messageHeader.getDisId());
        hearder.put("Interface_ID", this.messageHeader.getInterface_ID());
        hearder.put("MessageId", this.messageHeader.getMessageId());
        hearder.put("Receiver", this.messageHeader.getReceiver());
        hearder.put("SendDate", this.messageHeader.getSendDate());
        hearder.put("Sender", this.messageHeader.getSender());
        hearder.put("SendTime", this.messageHeader.getSendTime());
        returnJsonObject.put("MessageHeader", hearder);

        /**
         * 获取接口返回数据并进行BPM组装
         */

        List<BO> listParent = list.stream().filter(bo -> StringUtil.isEmpty(bo.getString("PARENT_LEVEL"))).collect(Collectors.toList());
        List<BO> sonConfigList = SDK.getBOAPI().query("BO_EU_SERVICE_GRANDSON").list();


        for (BO bo : listParent) {
            //参数头
            String head = bo.getString("HEAD");
            //类型
            String type = bo.getString("TYPE"); //对应表名
            String tableName = bo.getString("TABLE_NAME");
            if (type.equals("jsonObject")) {
                returnJsonObject.put("BINDID", bindId);
                returnJsonObject.put("BONAME", tableName);
            } else {
                List<BO> resultConfigList = sonConfigList.stream().filter(bo3 -> bo3.getBindId().equals(bo.getId())).collect(Collectors.toList());

                if (StringUtil.equals("obj", type)) {
                    BO dataBo = SDK.getBOAPI().query(tableName).bindId(bindId).detail();
                    JSONObject sonData = new JSONObject();
                    if (dataBo != null) {
                        //获取配置子表
                        if (StringUtil.isNotEmpty(spdm)) {
                            sonData = getDataInfo(resultConfigList, dataBo, sonData, spdm);
                        } else {
                            sonData = getDataInfo(resultConfigList, dataBo, sonData);
                        }
                        List<BO> configList = list.stream().filter(bo1 -> head.equals(bo1.getString("PARENT_LEVEL"))).collect(Collectors.toList());
                        for (BO bo1 : configList) {
                            //参数头
                            String head1 = bo1.getString("HEAD");
                            //类型
                            String type1 = bo1.getString("TYPE"); //对应表名
                            String tableName1 = bo1.getString("TABLE_NAME");
                            List<BO> resultConfigList1 = sonConfigList.stream().filter(bo3 -> bo3.getBindId().equals(bo1.getId())).collect(Collectors.toList());
                            if (type1.equals("obj")) {
                                BO dataBo1 = SDK.getBOAPI().query(tableName1).bindId(bindId).detail();
                                JSONObject sonData1 = new JSONObject();
                                if (dataBo1 != null) {
                                    if (StringUtil.isNotEmpty(spdm)) {
                                        sonData1 = getDataInfo(resultConfigList1, dataBo, sonData, spdm);
                                    } else {
                                        sonData1 = getDataInfo(resultConfigList1, dataBo, sonData);
                                    }

                                    sonData.put(head1, sonData1);
                                }
                            } else {
                                List<BO> dataList1 = SDK.getBOAPI().query(tableName1).bindId(bindId).list();
                                JSONArray jsonArray = new JSONArray();
                                if (dataList1 != null && dataList1.size() > 0) {
                                    for (int i = 0; i < dataList1.size(); i++) {
                                        BO dataBo11 = dataList1.get(i);
                                        JSONObject sonData11 = new JSONObject();
                                        //获取配置子表
                                        if (StringUtil.isNotEmpty(spdm)) {
                                            sonData11 = getDataInfo(resultConfigList1, dataBo11, sonData11, spdm);
                                        } else {
                                            sonData11 = getDataInfo(resultConfigList1, dataBo11, sonData11);
                                        }
                                        jsonArray.add(sonData11);
                                    }
                                    sonData.put(head1, jsonArray);
                                }
                            }
                        }
                    }
                    returnJsonObject.put(head, sonData);
                } else if (StringUtils.equals("list", type)) {
                    List<BO> dataList = SDK.getBOAPI().query(tableName).bindId(bindId).list();
                    if (tableName.equals("BO_EU_SAP_FIZCLIST")) {
                        dataList = SDK.getBOAPI().query(tableName).addQuery("ANLN1 IS NULL", null).addQuery("BINDID=", bindId).list();
                    }
                    JSONArray jsonArrayFater = new JSONArray();
                    if (dataList != null && dataList.size() > 0) {
                        for (int j = 0; j < dataList.size(); j++) {
                            BO dataBo = dataList.get(j);
                            JSONObject sonData = new JSONObject();
                            //获取配置子表
                            if (StringUtil.isNotEmpty(spdm)) {
                                sonData = getDataInfo(resultConfigList, dataBo, sonData, spdm);
                            } else {
                                sonData = getDataInfo(resultConfigList, dataBo, sonData);
                            }
                            List<BO> configList = list.stream().filter(bo1 -> head.equals(bo1.getString("PARENT_LEVEL"))).collect(Collectors.toList());
                            for (BO bo1 : configList) {
                                //参数头
                                String head1 = bo1.getString("HEAD");
                                //类型
                                String type1 = bo1.getString("TYPE"); //对应表名
                                String tableName1 = bo1.getString("TABLE_NAME");
                                List<BO> resultConfigList1 = sonConfigList.stream().filter(bo3 -> bo3.getBindId().equals(bo1.getId())).collect(Collectors.toList());
                                if (type1.equals("obj")) {
                                    BO dataBo1 = SDK.getBOAPI().query(tableName1).bindId(bindId).detail();
                                    JSONObject sonData1 = new JSONObject();
                                    if (dataBo1 != null) {
                                        if (StringUtil.isNotEmpty(spdm)) {
                                            sonData1 = getDataInfo(resultConfigList1, dataBo, sonData, spdm);
                                        } else {
                                            sonData1 = getDataInfo(resultConfigList1, dataBo, sonData);
                                        }
                                        sonData.put(head1, sonData1);
                                    }
                                } else {
                                    List<BO> dataList1 = SDK.getBOAPI().query(tableName1).bindId(bindId).list();
                                    if (tableName1.equals("BO_EU_SAP_FIZCLIST")) {
                                        dataList1 = SDK.getBOAPI().query(tableName1).addQuery("ANLN1 IS NULL", null).addQuery("BINDID=", bindId).list();
                                    }

                                    JSONArray jsonArray = new JSONArray();
                                    if (dataList1 != null && dataList1.size() > 0) {
                                        for (int i = 0; i < dataList1.size(); i++) {
                                            BO dataBo11 = dataList1.get(i);
                                            JSONObject sonData11 = new JSONObject();
                                            //获取配置子表
                                            if (StringUtil.isNotEmpty(spdm)) {
                                                sonData11 = getDataInfo(resultConfigList1, dataBo11, sonData11, spdm);
                                            } else {
                                                sonData11 = getDataInfo(resultConfigList1, dataBo11, sonData11);
                                            }
                                            jsonArray.add(sonData11);
                                        }
                                        sonData.put(head1, jsonArray);
                                    }
                                }
                            }
                            jsonArrayFater.add(sonData);
                        }
                    }
                    returnJsonObject.put(head, jsonArrayFater);

                }
            }
        }
        this.sendData = returnJsonObject;
    }

    public JSONObject getData(String head, String parentHead, Map<String, Object> dataMap, JSONObject jsonObject) {
        List<BO> configList = this.messageHeader.getGirdConfigBo();

        List<BO> list = configList.stream().filter(bo -> head.equals(bo.getString("PARENT_LEVEL"))).collect(Collectors.toList());
        if (list != null && list.size() > 0) {
            for (BO bo : list) {
                //参数头
                String nextHead = bo.getString("HEAD");
                JSONObject nowJsonObject = new JSONObject();
                JSONObject jsonObjectResult = getData(nextHead, head, dataMap, nowJsonObject);
                jsonObjectResult.put(head, dataMap.get(head));
                jsonObject.put(head, jsonObjectResult);
            }
        } else {
            /**
             * 开始拼接数据
             */
            //拿到上一层的对象
            jsonObject.put(head, dataMap.get(head));
        }
        return jsonObject;
    }

    /**
     * 数据处理（非原始数据）
     */
    public abstract void dueInterFaceData();

    /**
     * 迭代数据
     */
    public JSONObject createSendData(JSONObject returnJsonObject, String head, String bindId) {
        List<BO> configList = this.messageHeader.getGirdConfigBo();
        List<BO> list = configList.stream().filter(bo -> head.equals(bo.getString("HEAD"))).collect(Collectors.toList());
        for (BO bo : list) {
            //参数头
            String nowHead = bo.getString("HEAD");
            //类型
            String type = bo.getString("TYPE");
            //对应表名
            String tableName = bo.getString("TABLE_NAME");
            //获取字段配置表数据
            List<BO> sonConfigList = SDK.getBOAPI().query("BO_EU_SERVICE_GRANDSON").bindId(bo.getId()).list();
            if (StringUtil.equals("obj", type)) {
                BO dataBo = SDK.getBOAPI().query(tableName).bindId(bindId).detail();
                JSONObject sonData = new JSONObject();
                if (dataBo != null) {
                    //获取配置子表
                    sonData = getDataInfo(sonConfigList, dataBo, sonData);
                }
                returnJsonObject.put(nowHead, sonData);
                /**
                 * 获取下一级
                 */
                List<BO> listNext = configList.stream().filter(bo1 -> head.equals(bo1.getString("PARENT_LEVEL"))).collect(Collectors.toList());
                for (BO bo1 : listNext) {
                    String nextHead = bo1.getString("HEAD");
                    returnJsonObject.put(nextHead, createSendData(returnJsonObject, nextHead, bindId));
                }
            } else if (StringUtils.equals("list", type)) {
                List<BO> dataList = SDK.getBOAPI().query(tableName).bindId(bindId).list();
                JSONArray jsonArray = new JSONArray();
                if (dataList != null && dataList.size() > 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        BO dataBo = dataList.get(i);
                        JSONObject sonData = new JSONObject();
                        //获取配置子表
                        sonData = getDataInfo(sonConfigList, dataBo, sonData);
                        jsonArray.add(sonData);
                    }
                }
                returnJsonObject.put(nowHead, jsonArray);
                List<BO> listNext = configList.stream().filter(bo1 -> head.equals(bo1.getString("PARENT_LEVEL"))).collect(Collectors.toList());
                for (BO bo1 : listNext) {
                    String nextHead = bo1.getString("HEAD");
                    returnJsonObject.put(nextHead, createSendData(returnJsonObject, nextHead, bindId));
                }
            }
        }
        return returnJsonObject;
    }

    /**
     * 迭代数据
     */
    public Map<String, Object> createSendData1(String bindId) {
        List<BO> configList = this.messageHeader.getGirdConfigBo();
        Map<String, Object> map = new HashMap<>();
        for (BO bo : configList) {
            //参数头
            String head = bo.getString("HEAD");
            //类型
            String type = bo.getString("TYPE");
            //对应表名
            String tableName = bo.getString("TABLE_NAME");
            //获取字段配置表数据
            List<BO> sonConfigList = SDK.getBOAPI().query("BO_EU_SERVICE_GRANDSON").bindId(bo.getId()).list();
            if (StringUtil.equals("obj", type)) {
                BO dataBo = SDK.getBOAPI().query(tableName).bindId(bindId).detail();
                JSONObject sonData = new JSONObject();
                if (dataBo != null) {
                    //获取配置子表
                    sonData = getDataInfo(sonConfigList, dataBo, sonData);
                    map.put(head, sonData);
                }
            } else if (StringUtils.equals("list", type)) {
                List<BO> dataList = SDK.getBOAPI().query(tableName).bindId(bindId).list();
                JSONArray jsonArray = new JSONArray();
                if (dataList != null && dataList.size() > 0) {
                    for (int i = 0; i < dataList.size(); i++) {
                        BO dataBo = dataList.get(i);
                        JSONObject sonData = new JSONObject();
                        //获取配置子表
                        sonData = getDataInfo(sonConfigList, dataBo, sonData);
                        jsonArray.add(sonData);
                    }
                    map.put(head, jsonArray);
                }
            }
        }
        return map;
    }

    public static JSONObject getDataInfo(List<BO> sonConfigList, BO dataBo, JSONObject sonData) {
        String bindid = dataBo.getBindId();
        for (BO sonBo : sonConfigList) {
            String sendFieldName = sonBo.getString("SEND_FIELD_NAME");
            String sendFieldType = sonBo.getString("SEND_FIELD_TYPE");
            String sendIsEmpty = sonBo.getString("SEND_IS_EMPTY");
            String receiveFieldName = sonBo.getString("RECEIVE_FIELD_NAME");
            String receiveFieldType = sonBo.getString("RECEIVE_FIELD_TYPE");
            String receiveFieldEmpty = sonBo.getString("RECEIVE_FIELD_EMPTY");
            String sendValuetype = sonBo.getString("SEND_VALUETYPE");
            String receiveValueType = sonBo.getString("RECEIVE_VALUE_TYPE");
            //TODO 根据配置是否为空，数据类型补写校验逻辑
            if (sendValuetype.equals("固定值")) {
                sonData.put(receiveFieldName, sendFieldName);
            } else if (sendValuetype.equals("AT公式")) {
                String resultData = SDK.getRuleAPI().executeAtScript(sendFieldName, null, bindid, null, null);
                if (StringUtils.isNotEmpty(resultData)) {
                    if (StringUtils.contains(sendFieldType, "time")) {
                        try {
                            String result[] = sendFieldType.split("&&");
                            if (result.length == 1) {
                                // 定义输入时间格式
                                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
                                // 定义输出时间格式
                                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                if (StringUtil.isNotEmpty(resultData)) {
                                    Date date = outputFormat.parse(resultData);
                                    // 格式化 Date 对象为目标格式的字符串
                                    String valueNew = inputFormat.format(date);
                                    sonData.put(receiveFieldName, valueNew);
                                }
                            } else {
                                // 定义输入时间格式
                                SimpleDateFormat inputFormat = new SimpleDateFormat(result[1]);
                                // 定义输出时间格式
                                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                if (StringUtil.isNotEmpty(resultData)) {
                                    Date date = outputFormat.parse(resultData);
                                    // 格式化 Date 对象为目标格式的字符串
                                    String valueNew = inputFormat.format(date);
                                    sonData.put(receiveFieldName, valueNew);
                                }
                            }

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        sonData.put(receiveFieldName, resultData);
                    }
                }
            } else {
                if (StringUtils.isNotBlank(dataBo.getString(sendFieldName))) {
                    if (StringUtils.contains(sendFieldType, "time")) {
                        try {
                            String result[] = sendFieldType.split("&&");
                            if (result.length == 1) {
                                // 定义输入时间格式
                                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
                                // 定义输出时间格式
                                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                if (StringUtil.isNotEmpty(dataBo.getString(sendFieldName))) {
                                    Date date = outputFormat.parse(dataBo.getString(sendFieldName));
                                    // 格式化 Date 对象为目标格式的字符串
                                    String valueNew = inputFormat.format(date);
                                    sonData.put(receiveFieldName, valueNew);
                                }
                            } else {
                                // 定义输入时间格式
                                SimpleDateFormat inputFormat = new SimpleDateFormat(result[1]);
                                // 定义输出时间格式
                                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                if (StringUtil.isNotEmpty(dataBo.getString(sendFieldName))) {
                                    Date date = outputFormat.parse(dataBo.getString(sendFieldName));
                                    // 格式化 Date 对象为目标格式的字符串
                                    String valueNew = inputFormat.format(date);
                                    sonData.put(receiveFieldName, valueNew);
                                }
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        sonData.put(receiveFieldName, dataBo.getString(sendFieldName));
                    }
                } else {
                    sonData.put(receiveFieldName, "");
                }
            }
        }
        return sonData;
    }

    public static JSONObject getDataInfo(List<BO> sonConfigList, BO dataBo, JSONObject sonData, String SPDM) {
        String bindid = dataBo.getBindId();
        for (BO sonBo : sonConfigList) {
            String sendFieldName = sonBo.getString("SEND_FIELD_NAME");
            String sendFieldType = sonBo.getString("SEND_FIELD_TYPE");
            String sendIsEmpty = sonBo.getString("SEND_IS_EMPTY");
            String receiveFieldName = sonBo.getString("RECEIVE_FIELD_NAME");
            String receiveFieldType = sonBo.getString("RECEIVE_FIELD_TYPE");
            String receiveFieldEmpty = sonBo.getString("RECEIVE_FIELD_EMPTY");
            String sendValuetype = sonBo.getString("SEND_VALUETYPE");
            String receiveValueType = sonBo.getString("RECEIVE_VALUE_TYPE");
            //判断审批代码
            if (receiveFieldName.equals("FRGKZ")) {
                if (SPDM.equals("通过")) {
                    sonData.put(receiveFieldName, "A");
                }
                if (SPDM.equals("修改")) {
                    sonData.put(receiveFieldName, "M");
                }
                if (SPDM.equals("拒签")) {
                    sonData.put(receiveFieldName, "R");
                }
            } else {
                //TODO 根据配置是否为空，数据类型补写校验逻辑
                if (sendValuetype.equals("固定值")) {
                    sonData.put(receiveFieldName, sendFieldName);
                } else if (sendValuetype.equals("AT公式")) {
                    String resultData = SDK.getRuleAPI().executeAtScript(sendFieldName, null, bindid, null, null);
                    if (StringUtils.isNotBlank(resultData)) {
                        if (StringUtils.contains(sendFieldType, "time")) {
                            try {
                                String result[] = sendFieldType.split("&&");
                                if (result.length == 1) {
                                    // 定义输入时间格式
                                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
                                    // 定义输出时间格式
                                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    Date date = outputFormat.parse(resultData);
                                    // 格式化 Date 对象为目标格式的字符串
                                    String valueNew = inputFormat.format(date);
                                    sonData.put(receiveFieldName, valueNew);
                                } else {
                                    // 定义输入时间格式
                                    SimpleDateFormat inputFormat = new SimpleDateFormat(result[1]);
                                    // 定义输出时间格式
                                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                        Date date = outputFormat.parse(resultData);
                                        // 格式化 Date 对象为目标格式的字符串
                                        String valueNew = inputFormat.format(date);
                                        sonData.put(receiveFieldName, valueNew);
                                }

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        } else {
                            sonData.put(receiveFieldName, resultData);
                        }
                    }
                } else {
                    if (StringUtils.isNotBlank(dataBo.getString(sendFieldName))) {
                        if (StringUtils.contains(sendFieldType, "time")) {
                            try {
                                String result[] = sendFieldType.split("&&");
                                if (result.length == 1) {
                                    // 定义输入时间格式
                                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
                                    // 定义输出时间格式
                                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    if (StringUtil.isNotEmpty(dataBo.getString(sendFieldName))) {
                                        Date date = outputFormat.parse(dataBo.getString(sendFieldName));
                                        // 格式化 Date 对象为目标格式的字符串
                                        String valueNew = inputFormat.format(date);
                                        sonData.put(receiveFieldName, valueNew);
                                    }
                                } else {
                                    // 定义输入时间格式
                                    SimpleDateFormat inputFormat = new SimpleDateFormat(result[1]);
                                    // 定义输出时间格式
                                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    if (StringUtil.isNotEmpty(dataBo.getString(sendFieldName))) {
                                        Date date = outputFormat.parse(dataBo.getString(sendFieldName));
                                        // 格式化 Date 对象为目标格式的字符串
                                        String valueNew = inputFormat.format(date);
                                        sonData.put(receiveFieldName, valueNew);
                                    }
                                }

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        } else {
                            sonData.put(receiveFieldName, dataBo.getString(sendFieldName));
                        }
                    } else {
                        sonData.put(receiveFieldName, "");
                    }
                }
            }
        }
        return sonData;
    }
}
